package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private AuthorMapper authorMapper;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Resource(name = "minIOFileStorageService")
    private FileStorageService fileStorageService;

    @Value("${file.minio.prefix}")
    private String prefix;

    @Value("${file.minio.readPath}")
    private String readPath;

    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        //1.获取template模板对象
        try {
            Template template = configuration.getTemplate("article.ftl");
            //2.准备替换模板的数据（作者对应apUser id ,文章信息apArticle , 文章详情 content）
            Map params = new HashMap();
            //2.1准备文章内容详情
            params.put("content", JSON.parseArray(content,Map.class));
            //2.2准备文章信息
            params.put("article",apArticle);
            //2.3准备作者对应的app账户id
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            params.put("authorApUserId", apAuthor.getUserId());
            //3.基于数据替换模板 得到输出内容静态页
            StringWriter writer = new StringWriter();
            template.process(params,writer);
            String htmlContent = writer.toString();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(htmlContent.getBytes());
            //4.将得到的静态页面 上传到minio中
            //参数1：上传至哪个文件夹  参数2：文件名称    参数3：文件类型    参数4：输入流
            String store = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);
            //5.将上传成功的minio文件路径 设置ap_article中的static_url字段中
            apArticle.setStaticUrl(store);
            apArticleMapper.updateById(apArticle);
            log.info("成功生成文章静态页，静态页访问地址：{}", readPath+store);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            log.error("静态页面生成失败，失败原因：{}" + e.getCause());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"静态页面生成失败，失败原因：{}" + e.getCause());
        }
    }
}
